import { setupResizeEvent } from './events/resize'
import mixinEventListeners from './events/mixinEventListeners'
import createScope from './scope'
import { initToolbar } from './timeline/toolbar'
import { getWindowSize, initObjects, framer } from "@src/utils/utils"
import { landscapeShaderMaterial, canvasShaderMaterial, lineShaderMaterial } from '@src/core/shader'

import { loadBlobTextures, createGeographies, fetchObject } from '@src/timeline/__timeline_util'

function Incident () {
  this.__initDone = false

  // 参数
  this.$option = {
    // 上一帧 时间
    lastFrameTime: framer(),
    // 启用帧
    frameElapsed: 0,
  }

  // 帮助数据及函数
  this.$scope = createScope()

  // WEBGL 的大小
  this.$gl = {
    ...getWindowSize(),
  }

  // camera
  this.$camera = {
    introTime: 0,
    introLength: 4000,

    // 相机 y
    cameraY: 0,
    // 相机运动
    cameraZMotion: 0,
    // 相机目标
    cameraZTarget: null,
    // 相机 X 0
    cameraXOffset: 0,
    // 相机 Y 0.5
    cameraYOffset: 0.5,
  }

  this.objectIndex = {};
  this.blobIndex = {};

  /**
   * 环境着色器
   * @type {THREE.ShaderMaterial}
   */
  this.landscapeShaderMaterial = landscapeShaderMaterial

  /**
   * 素材着色器
   * @type {THREE.ShaderMaterial}
   */
  this.canvasShaderMaterial = canvasShaderMaterial

  /**
   * 线条着色器
   * @type {THREE.ShaderMaterial}
   */
  this.lineShaderMaterial = lineShaderMaterial

  // 初始化 object
  this.$objects = initObjects()

  this.toolBar3D = new THREE.Object3D()
  this.toolBar3D.buttons = []

  // 弹框 覆盖物
  this.$overlays = document.getElementById('overlays')

  // 地理位置
  this.loadingPercentageMax = 0
  this.geographies = createGeographies(this)

  // 贴图
  this.blobTextures = loadBlobTextures(this)

  this.init()
}

Incident.prototype.init = function() {
  if (!this.__initDone) {
    this.__initDone = true

    this.initRenderer()
    this.initSceneCamera()

    this.initLanes()
    this.initLandscape()
    // this.initIntro()

    setupResizeEvent(this)

    mixinEventListeners(this)

    // 背景假山
    fetchObject(object => {
      this.createTerrain(object)
    })

    initToolbar(this)

    console.log(this)
    this.tick();
  }
};

/**
 * 创建轨道
 */
Incident.prototype.initLanes = function() {
  this.lanes = this.createLanes();
  this.dividers = this.lanes.dividers;
  this.lines = this.lanes.lines;
  this.linesPlane = this.lanes.linesPlane;
  this.scene.add(this.lanes);
}

Incident.prototype.render = function() {
  this.renderer.autoClear = false;
  this.renderer.clear();
  this.renderer.render(this.scene, this.camera);
  this.renderer.render(this.labelScene, this.camera);
};

export default Incident
